#! /usr/bin python
import requests, json, sys, time


class WorkWechat():
    def __init__(self):
        self.corp_id = ''  #企业ID   https://work.weixin.qq.com/wework_admin/frame#profile
        self.corp_secret = ''
        self.agent_id = '1000002'   #小程序id  https://work.weixin.qq.com/wework_admin/frame#apps
        self.token = '123'
        self.title = ''
        self.msg = ''
        self.headers = {
            'Accept': '*/*',
            'Accept-Encoding': 'gzip, deflate, sdch',
            'Accept-Language': 'zh-CN,zh;q=0.8,en;q=0.6',
            'Connection': 'keep-alive',
            'Content-Type': 'application/x-www-form-urlencoded',
            'Referer': 'https://qyapi.weixin.qq.com/?{}'.format(int(time.time())),
            'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:58.0) Gecko/20100101 Firefox/58.0',
            'Cookie': '_ntes_nnid=2da511387474575b77a1e0a13d6df57e,1527507977129; _ntes_nuid=2da511387474575b77a1e0a13d6df57e; vinfo_n_f_l_n3=2e40f7fc7366d16d.1.0.1527507977156.0.1527508882506; usertrack=ezq0plswU1Wdn48dA1XZAg==; _ga=GA1.2.660826221.1529893720; __f_=1532395985802; _iuqxldmzr_=32; __utmz=94650624.1534308847.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); WM_TID=Z1Jm%2FrA9KHL%2BHxOBomtGeqTrwVoLDJtd; __utmc=94650624; playerid=19834031; JSESSIONID-WYYY=xMEDtoZO%2BiRzkY3QR%5ChVyupwUBwFivY%2BBAyCPJNlEcmafmm94pa%2BquYglywlQBWN4gKk90XO0Dlx1JCU%2BJ3CmBnV8jHBu5Rzj%2BE%5CcvpBRf%2B%2FI%2BUx71SY5lEsfeJKD6SpzZNCw%2Bae%5Ccnl%5CGv7diN8FZ3Hshs6Bh9Aiooh6sjZkafmwztx%3A1534325997512; __utma=94650624.660826221.1529893720.1534319610.1534324198.4; __utmb=94650624.2.10.1534324198; WM_NI=ZzfxoKxGKsmy3YW9fXsRoCollXv7f8VCQELJt4javuXbEgmayUVzE2FcppvHW174lpq1iEeIUNhLS69AeEf%2B%2Fsf5BGaLSIbLfmBZDUozXUnTXRxo2%2BpZmH79ev2gI8%2FqdTI%3D; WM_NIKE=9ca17ae2e6ffcda170e2e6eeb5ec398bbcbaa8f3549aeaa494e763938aa68dc952f68d8585b77aba95b8baf22af0fea7c3b92a9aa6aa99ee41bc998594f073f18799dae554b18ea1a4ee68b088bad8e534969d9fa6cf42b8eca682f57f9cbe8b88f06bbb8b9a9bc83a86bdc091f54495eff9d5ef7cb3efa7a6e8439792a8add23efb9faba6e521edadaad6c14da3949daae148a6b38ebbc75fada698b6ed609c8eb890b121b486a3a9b633a7aafe88cc34edafacb5cc37e2a3'
        }
        self.run()

    def writeLog(self, msg):
        with open('log.log', 'a+') as f:
            f.write('{}>>{}\n'.format(time.strftime('%Y-%m-%d %H:%M:%S'), str(msg)))
        return

    def get_access_token(self):
        url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={}&corpsecret={}'.format(self.corp_id, self.corp_secret)
        r = requests.get(url, headers=self.headers)
        r_json = r.json()
        r.close()
        if r_json['errcode'] == 0:
            self.token = r_json['access_token']
            print(self.token)
            return True
        return False

    def SendWorkWechatMsg(self):
        print(self.msg)
        send_url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={}'.format(self.token)
        msg_params = {
            'touser': '@all',
            "msgtype": "textcard",
            'agentid': self.agent_id,
            'text': {
                'content': self.msg
            },
            'markdown': {
                'content': self.msg
            },
            "textcard": {
                "title": self.title,
                "description": self.msg,
                "url": "http://106.2.230.69:1220",
                # "btntxt": "更多"
            },
            'safe': 0
        }
        print(msg_params)
        r = requests.post(send_url, data=json.dumps(msg_params), headers=self.headers)
        re_json = r.json()

        if re_json['errcode'] == 41001 or re_json['errcode']  ==40014:
            print(re_json)
            self.get_access_token()
            self.SendWorkWechatMsg()
            self.writeLog(re_json)

    def run(self):
        if len(sys.argv) == 1:
            print('error')
            return
        # self.get_access_token()
        self.writeLog('run')
        self.title = sys.argv[2]
        self.msg = sys.argv[3]
        # for i in range(1, len(sys.argv)):
        #     self.writeLog(sys.argv[i])
        #     self.msg += str(sys.argv[i])
        self.SendWorkWechatMsg()
        print('end')
        return
if __name__ == '__main__':
    WW = WorkWechat()
